Push Notification Integration

Push notification functionality depends upon piStats analytics, so please make sure the analytic integration is also completed.

Javascript

Pre-requisite

Before integrating push notifications, piStats library should be integrated with the site. Here are detailed steps PiStats Integration

https:// implementation

  1. Integrate FCM library: https://firebase.google.com/docs/cloud-messaging/js/client
  2. Create a custom popup on the website which would have two Actions “Allow” and “Block”.
  3. Create a domain level cookie and store user action “Allow” or “Block”. Doing so, let’s us ask the user again after a certain period of time. For example if the user had “Blocked” the notifications we can store it in cookie for 30 days, and after 30 days when the user comes back we can ask him again.
  4. If the user chooses to “Block” the push notifications, store it in cookie.
  5. If the user chooses to “Allow” the push notifications, store it in cookie and then open the FCM allow popup
    1. On the callback of FCM Allow, call FCM methods to Generate FCM token. Here is the link FCM Token generation
    2. On the callback of FCM token, we need to call piStats subscriptions passing in the FCM token and names of the topics to subscribe and unsubscribe:
piStats.subscribeNotification(<fcmToken>,<subscriptionTopicArray>,<unsubscribeTopicArray>)

Android

  1. Add the following permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
  1. Add Firebase SDK: Please follow the instructons in the link below:
    https://firebase.google.com/docs/cloud-messaging/android/client
  2. Add piStats SDK to your app:
    • In Android studio ‘File > New > New Module’ → Select ‘Import .jar/.aar’ package
    • import piStats.aar
    • In build.gradle add:
compile project(':pistats')
  1. Add the following in ‘onCreate()’ of the application
PiStats.getInstance().init(this, <PropertyId>);

After piStats SDK has been initialized we can track the following type of events:

  1. Registration :
  • After we have received the FCM registration token we need to register the device with piStats for push notification.
public class PistatsRegistrationReceiver extends BroadcastReceiver {

@Override
 public void onReceive(Context context, Intent intent) {
     if (!TextUtils.isEmpty(<language>))
         subscriptionEventForPiStat(<language>);
     Event event = new Event();
     event.setPropertyId(<PropertyId>);
     event.setLanguage(<language>);
     event.setRegistrationId(<FCM token>);
     event.setCustId(<customerId>);
     PiStats.getInstance().registrationEvent(event);
 }

 public static void subscriptionEventForPiStat(String language) {
     if (<user opted out for pushNotificaiton>)
         return;
     try {
         Event event = new Event();
         event.setPropertyId(<PropertyId>);
         event.setLanguage(language);
         event.setRegistrationId(<FCMToken>);
         ArrayList<String> arrayListForSubscription = new ArrayList<>();
         arrayListForSubscription.add(<TopicToSubcribe>);
         arrayListForSubscription.add(<TopicToSubcribe>);
         ......
         ......
         event.setTopicArrayListForSubscribe(arrayListForSubscription);

         PiStats.getInstance().subscriptionEvent(event);
     } catch (Exception e) {

     }
 }

}

  • Register the broadcast receiver in manifest
<receiver
  android:name=".PistatsRegistrationReceiver"
  android:enabled="true"
  android:exported="true"
  tools:ignore="ExportedReceiver">

   <intent-filter>
      <action android:name="com.pistats.registration.action"/>
   </intent-filter>
</receiver>
  • Call registration event
Event event = new Event();

event.setPropertyId(<PropertyId>);
event.setLangauageUser(<Language>);
event.setRegistrationId(<FCMToken>);
event.setCustId(<customerId>);

PiStats.getInstance().registrationEvent(event);
  1. Subscription: Subscription event is used to subscribe and unsubscribe users to push notification topics
Event event = new Event();

event.setPropertyId(<PropertyId>);
       event.setLangauageUser(<Language>);
       event.setRegistrationId(<FCMToken>);
       ArrayList<String> arrayListForSubscription=new ArrayList<>();

 /* Subscribe to topics */

     arrayListForSubscription.add(<Topic1>);
     arrayListForSubscription.add(<Topic2>);
     arrayListForSubscription.add(<Topic3>);
     event.setTopicArrayListForSubscribe(arrayListForSubscription);
     ArrayList<String> arrayListForUnSubscription = new ArrayList<>();

 /* Unsubscribe from topics */

 arrayListForUnSubscription.add(<Topic1>);
     arrayListForUnSubscription.add(<Topic2>);
     arrayListForUnSubscription.add(<Topic3>);
     arrayListForUnSubscription.add(<Topic4>);

 event.setTopicArrayListForUnsubscribe(arrayListForUnSubscription);

 PiStats.getInstance().subscriptionEvent(event);
  1. Load: This event is used to track all the different pages/screens a user visits. This would be the most frequently used event in the app. Not only does this event keep track of user browsing history but also combines referral information as well.
LoadEvent event = new LoadEvent();

      event.setEventName("PageLoad");
      event.setPropertyId(<PropertyId>);
      event.setLangauageUser(<Language>);
      event.setContentId("contentId");
      event.setReferrerType(<ReferrerType>);
      event.setReferrerOrigin(<ReferrerOrigin>);
      event.setReferrerMedium(<ReferrerMedium>);

    PiStats.getInstance().pageLoadEvent(event);
  1. Opt-out: In some apps user preference includes switching off the push notification completely. If your app supports such an option, use this event to stop push notifications for the particular user.
Event event = new Event();

 event.setPropertyId(<PropertyId>);
     event.setLangauageUser(<Language>);
     event.setRegistrationId(<FCMToken>);
     ArrayList<String> arrayListForTopicUnSubscribe=new ArrayList<>();

 /*Add topics to unsubscribe*/

     arrayListForTopicUnSubscribe.add(<Topic1>);
     arrayListForTopicUnSubscribe.add(<Topic2>);
     arrayListForTopicUnSubscribe.add(<Topic3>);
     event.setTopicArrayListForUnsubscribe(arrayListForTopicUnSubscribe);

PiStats.getInstance().optOutEvent(event);
  1. Opt-in: Opposite of the “opt-out” event if the user selects the option to receive notifications in the app, call this event to switch the push notifications back on for the user.
Event event = new Event();

     event.setPropertyId(<PropertyId>);
     event.setLangauageUser(<Language>);
     event.setRegistrationId(<FCMToken>);
     ArrayList<String> arrayListForTopicSubscribe=new ArrayList<>();

 /*Add topics to subscribe*/

     arrayListForTopicSubscribe.add(<Topic1>);
     arrayListForTopicSubscribe.add(<Topic2>);
     arrayListForTopicSubscribe.add(<Topic3>);
     event.setTopicArrayListForSubscribe(arrayListForTopicSubscribe);

PiStats.getInstance().optInEvent(event);

iOS - Objective-C

  1. Add the following permissions in the app’s plist file:
  • Location
  • Notifications
  1. Add piStats SDK to the X-code project
  2. Add Firebase SDK: Please follow the instructons in the link below: https://firebase.google.com/docs/cloud-messaging/ios/client
  3. Import piStats in AppDelegate.m
import <pistats/PistatsManage.h>
  1. Initialize piStats in application:didFinishLaunchingWithOptions
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

 [[PistatsManage getInstance]initWithProperty:PiStatsPropertyid];

}
  1. Implement observer: Add kPiStatsObserverNotification in application:didFinishLaunchingWithOptions
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {
       [PistatsManage getInstance];
       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pistatObserverCall:)
       name:kPiStatsObserverNotification object:nil];
  }
(void)pistatObserverCall:(NSNotification*)notification
  {
       [self registrationCallForPistats];
       [self subscriptionCallForPistats];
  }

After piStats SDK has been initialized we can track the following type of events:

  1. Registration :
  • After we have received the FCM registration token we need to register the device with piStats for push notification.
NewEvent *event           = [[NewEvent alloc]init];

     event.Language               = @“Language name”,
     event.SubscribeToTopics      = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
     event.FCMToken               = @“Firebase token”
     event.UnsubscribeFromTopics  = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
     event.PropertyId             = PiStatsPropertyid;
     event.deviceUDID             = @“device UDID”;

[[PistatsManage getInstance]registerForDevice:PiStatsPropertyid WithEvent:event];
  1. Subscription: Subscription event is used to subscribe and unsubscribe users to push notification topics
  • For push notifications the subscription call is best placed as a callback from FCM registration
(void)tokenRefreshNotification:(NSNotification *)notification
  {
      if(![CurrentFCMPushToken isEqualToString:[userDefaults objectForKey:FCMPushToken])
       {
          [[PistatsManage getInstance]registerForDevice:PiStatsPropertyid WithEvent:event]; // Registration call for piStats
       }
  }
  • piStats subscription
 NewEvent *event             = [[NewEvent alloc]init];

   event.Language                = @“Language name”,
   event.SubscribeToTopics         = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
   event.FCMToken              = @“Firebase token”
   event.UnsubscribeFromTopics     = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
   event.PropertyId              = PiStatsPropertyid;
   event.deviceUDID              = @“device UDID”;

[[PistatsManage getInstance]subscribeForNotification:PiStatsPropertyid WithEvent:event];
  • piStats unsubscribe
NewEvent *event       = [[NewEvent alloc]init];
    event.Language        = [userDefaults valueForKey:ChannelType],
    event.SubscribeToTopics     = [[NSArray alloc]initWithObjects:currentChannel, nil];
    event.UnsubscribeFromTopics = [[NSArray alloc]initWithObjects:lastChannel, nil];
    event.FCMToken        = [userDefaults valueForKey:FCMPushToken],
    event.ProprtyId       = PiStatsPropertyid;
    event.deviceUDID      = [userDefaults valueForKey:UserUDID];

[[PistatsManage getInstance]subscribeForNotification:event];
  1. Load: This event is used to track all the different pages/screens a user visits. This would be the most frequently used event in the app. Not only does this event keep track of user browsing history but also combines referral information as well.
NewEvent *event       = [[NewEvent alloc]init];

    event.EventName       = @"PageLoad";
    event.Language        = @“Language name”;
    event.ReferrerOrigin  = @"internal";
    event.ReferrerMedium  = @"page";
    event.ReferrerType    = @“type”;
    event.EventTimestamp  = @“Timestamp” /* ISO date and time formate
    event.PropertyId      = PiStatsPropertyid;
    event.ContentID       = @“ContentID”;
    event.deviceUDID      =  @“device UDID”;

[[PistatsManage getInstance]loadviewController:self WithEvent:event];
  1. Opt-out: In some apps user preference includes switching off the push notification completely. If your app supports such an option, use this event to stop push notifications for the particular user.
NewEvent *event             = [[NewEvent alloc]init];

      event.Language              = @“Language name”,
      event.SubscribeToTopics        = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
      event.FCMToken                 = @“Firebase token”
      event.UnsubscribeFromTopics   = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
      event.PropertyId               = PiStatsPropertyid;
      event.deviceUDID               = @“device UDID”;

[[PistatsManage getInstance]deviceSwitchOffForNotification:PiStatsPropertyid WithEvent:event];
  1. Opt-in: Opposite of the “opt-out” event if the user selects the option to receive notifications in the app, call this event to switch the push notifications back on for the user.
NewEvent *event             = [[NewEvent alloc]init];

        event.Language              = @“Language name”,
        event.SubscribeToTopics        = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
        event.FCMToken                = @“Firebase token”
        event.UnsubscribeFromTopics   = [[NSArray alloc]initWithObjects:@“topic1”,@“topic2”, nil];
        event.PropertyId            = PiStatsPropertyid;
        event.deviceUDID          = @“device UDID”;

[[PistatsManage getInstance]deviceSwitchOnForNotification:PiStatsPropertyid WithEvent:event];

iOS - Swift

  1. Add the following permissions in the app’s plist file:
  • Location
  • Notifications
  1. Add piStats SDK to the X-code project and import two files in project bridging header
#import <pistats/PistatsManage.h>
#import <pistats/NewEvent.h>
  1. Add Firebase SDK: Please follow the instructons in the link below: https://firebase.google.com/docs/cloud-messaging/ios/client
  2. Import piStats in AppDelegate
import pistats
  1. Initialize piStats in application:didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
   {
     PistasManage.getInstance()(property:PiStatsPropertyid)
   }

}
  1. Implement observer: Add kPiStatsObserverNotification in application:didFinishLaunchingWithOptions
 NotificationCenter.default.addObserver(self, selector: Selector(("pistatObserverCall:")), name: NSNotification.Name.piStatsObserver, object: nil)

func pistatObserverCall(_ notification: Notification) {

    self.registrationCallForPistats()
    self.subscribeCallForPistats()
}

After piStats SDK has been initialized we can track the following type of events:

  1. Registration :
  • After we have received the FCM registration token we need to register the device with piStats for push notification.
if let fcmTokenDefaultValue = userDefault.value(forKey:pistatsFCMToken)
    {
        fcmTokenDefaultValue = deviceTokenValue as! String
    }
        let notifnEvent = NewEvent()
        notifnEvent.language = currentLanguage()
        notifnEvent.fcmToken = fcmToken  /* Firebase token Mandatory  */
        if let deviceTokenValue = userDefault.value(forKey:pistatsDeviceToken)
        {
            notifnEvent.deviceUDID = deviceTokenValue as! String
        }
        notifnEvent.proprtyId = pistatsPropertyId
        notifnEvent.eventTimestamp  = getTimeandDateInISO()

  (PistatsManage.getInstance() as AnyObject).register(forDevice: notifnEvent)
  1. Subscription: Subscription event is used to subscribe and unsubscribe users to push notification topics
  • For push notifications the subscription call is best placed as a callback from FCM registration
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
     var fcmTokenDefaultValue = ""
     if let deviceTokenValue = userDefault.value(forKey:pistatsFCMToken)
     {
         fcmTokenDefaultValue = deviceTokenValue as! String
     }

     if(fcmToken != fcmTokenDefaultValue)
     {
         let notifnEvent = NewEvent()
         notifnEvent.language = currentLanguage()
         notifnEvent.fcmToken = fcmToken  /* Firebase token Mandatory  */
         if let deviceTokenValue = userDefault.value(forKey:pistatsDeviceToken)
         {
             notifnEvent.deviceUDID = deviceTokenValue as! String
         }
         notifnEvent.proprtyId = pistatsPropertyId
         notifnEvent.eventTimestamp  = getTimeandDateInISO()

         (PistatsManage.getInstance() as AnyObject).register(forDevice: notifnEvent)
         userDefault.set(fcmToken, forKey:pistatsFCMToken)
     }
 }
  • piStats subscription
let event = NewEvent()
  event.language = currentLanguage()
  event.subscribeToTopics = subscribeTopics /* Pass array of all topics */
  event.fcmToken = FCMTokenValue as! String
  event.propertyId = pistatsPropertyId
  event.eventTimestamp = getTimeandDateInISO()

(PistatsManage.getInstance()as AnyObject).subscribe(forNotification:event)
  • piStats unsubscribe
let notifnEvent = NewEvent()
  notifnEvent.language = currentLanguage()
  notifnEvent.subscribeToTopics = subscribeTopics /* Pass array of all subscribe topics */
  notifnEvent.unsubscribeFromTopics = unsubscribeTopics /* Pass array of all unsubscribe topics */
if let FCMTokenValue = userDefault.value(forKey:PistatsFCMToken) /*Pass FCM token */
  {
      notifnEvent.fcmToken = FCMTokenValue as! String
  }
if let deviceTokenValue = userDefault.value(forKey:pistatsDeviceToken)  /*Pass Device token */
  {
     notifnEvent.deviceUDID = deviceTokenValue as! String
  }
  notifnEvent.proprtyId  = pistatsPropertyId

(PistatsManage.getInstance() as AnyObject).subscribe(forNotification:notifnEvent)
  1. Load: This event is used to track all the different pages/screens a user visits. This would be the most frequently used event in the app. Not only does this event keep track of user browsing history but also combines referral information as well.
let event = NewEvent()
   event.eventTimestamp = currentFormattedDate()
   event.language = currentLanguage()
   event.proprtyId = pistatsPropertyId
   event.referrerOrigin = RefferOrigin
   event.referrerMedium = sectionName
   event.contentID = newsID
 (PistatsManage.getInstance() as AnyObject).loadviewController(self, with:event)
  1. Opt-out: In some apps user preference includes switching off the push notification completely. If your app supports such an option, use this event to stop push notifications for the particular user.
var event = NewEvent()
    event.language = userDefaults.value(forKey:   ChannelType),
    event.subscribeToTopics = [currentChannel]
    event.fcmToken = userDefaults.value(forKey: FCMPushToken),
    event.proprtyId = PiStatsPropertyid
    event.deviceUDID = userDefaults.value(forKey: UserUDID)
    event.eventTimestamp = Utility.getTimeandDateInISO()
PistatsManage.getInstance().deviceSwitchOff(forNotification: event)
  1. Opt-in: Opposite of the “opt-out” event if the user selects the option to receive notifications in the app, call this event to switch the push notifications back on for the user.
var event = NewEvent()
    event.language = userDefaults.value(forKey: ChannelType),
    event.subscribeToTopics = [currentChannel]
    event.fcmToken = userDefaults.value(forKey: FCMPushToken),
    event.proprtyId = PiStatsPropertyid
    event.deviceUDID = userDefaults.value(forKey: UserUDID)
    event.eventTimestamp = Utility.getTimeandDateInISO()
PistatsManage.getInstance().deviceSwitchOn(forNotification: event)